package com.character_display_picture;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;

/**
 * @Author: ZhangYue26
 * @Date: @date 2020-05-14 10:44
 * @Description: 图片转Ascii字符画
 */

public class AsciiPic {

    /**
     * @param path
     *            图片路径
     */
    public static void createAsciiPic(final String path) throws FileNotFoundException {
        String fileName = UUID.randomUUID().toString().replace("-", "");
        File file = new File("C:\\Users\\zhangyue26\\Desktop\\" + fileName + ".txt");
        OutputStream outputStream = new FileOutputStream(file);
        final String base = "@#&$%*o!;.";// 字符串由复杂到简单
        try {
            final BufferedImage image = ImageIO.read(new File(path));
            for (int y = 0; y < image.getHeight(); y += 2) {
                for (int x = 0; x < image.getWidth(); x++) {
                    final int pixel = image.getRGB(x, y);
                    final int r = (pixel & 0xff0000) >> 16, g = (pixel & 0xff00) >> 8, b = pixel & 0xff;
                    final float gray = 0.299f * r + 0.578f * g + 0.114f * b;
                    final int index = Math.round(gray * (base.length() + 1) / 255);
                    String result = index >= base.length() ? " " : String.valueOf(base.charAt(index));
                    System.out.print(result);
                    outputStream.write((result).getBytes("UTF-8"));
                }
                outputStream.write("\r\n".getBytes("UTF-8"));
                System.out.println();
                outputStream.flush();
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * test
     *
     * @param args
     */
    public static void main(final String[] args) throws FileNotFoundException {
        AsciiPic.createAsciiPic("C:\\Users\\zhangyue26\\Desktop\\buxie.jpg");
    }




}
